package com.example.demo.leetcode.codetop.bytedance;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xujimou
 * @version 2.0
 * @Description
 * 输入：head = [1,2,3,3,4,4,5]
 * 输出：[1,2,5]
 * 链表中节点数目在范围 [0, 300] 内
 * -100 <= Node.val <= 100
 * 题目数据保证链表已经按升序 排列
 *
 * @date 2022/2/21 14:10
 */
public class Node_删除重复出现的节点 {

     public class ListNode {
         int val;
         ListNode next;
         ListNode() {}
         ListNode(int val) { this.val = val; }
         ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     }

     /**
      * @Desciption: 遍历一次，塞入map key(值)-value(次數), 二次遍历的时候 value>1的删除
      *
      * @param head:
      */
    public ListNode deleteDuplicates(ListNode head) {

        Map<Integer,Integer> map  = new HashMap<>();
        firstRead(map,head);
        ListNode node = new ListNode(Integer.MAX_VALUE);
        node.next = head;
        return removeDuplicates(map,node);
    }

    public void firstRead(Map<Integer,Integer> map,ListNode head){
        while(head != null){
            if(map.containsKey(head.val)){
                Integer count = map.get(head.val);
                map.put(head.val,++count);
            }else{
                map.put(head.val,1);
            }
            head = head.next;
        }
    }

    /**
     * @Desciption:
     *   x -> 1 -> 2 ->3 ->3 ->4 ->4 ->5
     *  start
     * @param map:
     * @param head:
     */
    public ListNode removeDuplicates(Map<Integer,Integer> map,ListNode head){
        ListNode start = head;

        while(head.next != null){
            if(map.get(head.next.val)>1){
                head.next = head.next.next;
            }else{
                head = head.next;
            }
        }
        return start.next;
    }



    /**
     * @Desciption: 递归解法
     * @param head:
     */
    public ListNode deleteDuplicates2(ListNode head) {
        ListNode result = new ListNode(Integer.MAX_VALUE);
        ListNode pre = new ListNode(Integer.MIN_VALUE);
        ListNode process = process(head,pre, result);
        return process.next;
    }

    public ListNode process(ListNode head,ListNode pre,ListNode result){
        ListNode res = result;

        if(head == null){
            result.next = null;
            return res;
        }

        if(head.next == null && head.val == pre.val){
            result.next = null;
            return res;
        }

        if(head.next == null && head.val != pre.val){
            result.next = head;
            return res;
        }

        if(head.val == head.next.val || pre.val == head.val){
            process(head.next,head,result);
        }

        if(head.val != head.next.val && head.val != pre.val){
            result.next = head;
            process(head.next, head, result.next);
        }
        return res;
    }



}
